package algorithm.linklist;

class Node1 {
    int value;
    Node1 next;

    public Node1(int value) {
        this.value = value;
    }

    public Node1 revert() {
        Node1 head = this;
        Node1 pre = null;
        Node1 next;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public Node1 del(int val) {
        Node1 head = this;
        while (head != null) {
            if (head.value != val) {
                break;
            }
            head = head.next;
        }
        Node1 pre = head;
        Node1 cur = head;
        while (cur != null) {
            if (cur.value == val) {
                // 需要删除
                // pre的下指针指向当前节点的下指针
                pre.next = cur.next;
            } else {
                // 不需要删除，pre往后走一步
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    public static void main(String[] args) {
        Node1 node = getRandomNode(5, 10);
        printNode(node);
        printNode(node.revert());
    }

    public static Node1 getRandomNode(int len, int maxVal) {
        Node1 node = new Node1((int) (Math.random() * maxVal));
        len--;
        Node1 next = null;
        while (len > 0) {
            if (node.next == null) {
                node.next = new Node1((int) (Math.random() * maxVal));
                next = node.next;
            } else {
                next.next = new Node1((int) (Math.random() * maxVal));
                next = next.next;
            }
            len--;
        }
        return node;
    }

    private static void printNode(Node1 node) {
        while (node != null) {
            System.out.print(node.value + " -> ");
            node = node.next;
        }
        System.out.println();
    }

}

